<template>
  <div>
    <div>
      <div style="margin: 10px 0 10px 100px">
        <Upload
          action="http://8.136.118.105:8008/file/uploadImage"
          list-type="picture-card"
          v-model:file-list="fileList"
          @change="handleUploadChange"
        >
          <div v-if="fileList.length < 8">
            <plus-outlined />
            <div class="ant-upload-text">图片上传</div>
          </div>
        </Upload>
      </div>
      <a-modal :visible="previewVisible" :footer="null">
        <img style="width: 100%" :src="previewImage" />
      </a-modal>

      <div>
        <div style="margin-bottom: 20px">
          <div v-for="(comment, index) in comments" :key="index">
            <div style="display: flex; align-items: center">
              <div style="margin-right: 10px; width: 130px; text-align: right; line-height: 30px"
                >评论内容</div
              >
              <a-input
                v-model:value="comment.content"
                 style="width: 80%"
                :placeholder="t('sys.configuration.commenttext')"
              />
              <!-- <a-button type="primary" @click="add">添加</a-button> -->
              <Icon
                icon="ant-design:plus-circle-outlined"
                @click="add"
                :size="30"
                v-if="index == 0"
                style="margin-left: 5px"
              />

              <Icon
                icon="ant-design:close-circle-outlined"
                @click="del(index)"
                :size="30"
                v-if="index != 0"
                style="margin-left: 5px"
              />
              <!-- <a-button @click="del(index)" style="margin: 0 5px" v-if="index > 0"> {{ t('sys.configuration.delete') }} </a-button> -->
              <a-button style="margin: 0 5px" @click="openImageSelector(index, 'comment')"
                >选择图片</a-button
              >
              <div>
                <span v-for="(image, imgIndex) in comment.photos" :key="imgIndex">
                  <img :src="image" style="width: 50px; height: 50px; margin-left: 10px" />
                </span>
              </div>
            </div>
          </div>
        </div>
        <div style="margin-bottom: 20px">
          <div v-for="(comment, index) in chats" :key="index" style="margin: 10px 0">
            <div style="display: flex; align-items: center">
              <div style="margin-right: 10px; width: 130px; text-align: right; line-height: 30px"
                >私信内容</div
              >
              <a-input
                v-model:value="comment.content"
                  style="width: 80%"
                placeholder="请输入私信内容"
              />
              <Icon
                icon="ant-design:plus-circle-outlined"
                @click="addChats"
                :size="30"
                v-if="index == 0"
                style="margin-left: 5px"
              />
              <Icon
                icon="ant-design:close-circle-outlined"
                @click="delChats(index)"
                :size="30"
                v-if="index != 0"
                style="margin-left: 5px"
              />
              <!-- <a-button @click="delChats(index)" style="margin: 0 5px" v-if="index > 0"
              > {{ t('sys.configuration.delete') }} </a-button
            > -->
              <a-button style="margin: 0 5px" @click="openImageSelector(index, 'chat')"
                >选择图片</a-button
              >
              <div>
                <span v-for="(image, imgIndex) in comment.photos" :key="imgIndex">
                  <img :src="image" style="width: 50px; height: 50px; margin-left: 10px" />
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Modal v-model:visible="imgvisible" style="top: 400px" title="图片选择" @ok="handleOkimg">
      <CheckboxGroup v-model:value="selectedImagesA">
        <div v-for="(image, index) in selectedImages" :key="index">
          <Checkbox :value="image">
            <img :src="image" style="width: 100px; height: 100px" />
          </Checkbox>
        </div>
      </CheckboxGroup>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
  import { useModal } from '@/components/Modal';
  import DetailView from './DetailView.vue';
  import Icon from '@/components/Icon/Icon.vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getTaskDetailApi } from '@/api/demo/Task';
  import {
    Card,
    Textarea,
    Modal,
    CheckboxGroup,
    Checkbox,
    Upload,
    FormItem,
    Tooltip,
    Progress,
  } from 'ant-design-vue';
  import { ref, computed, unref, h } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { getDeptList } from '@/api/demo/system';
  import { createTaskListApi, listPageApi, createTaskApi, updateTaskApi } from '@/api/demo/Task';
  import { getlistAPI, dataDeleteAPI } from '@/api/demo/video';
  import { getTasklistAPI } from '@/api/demo/InformationMatching';
  import { constant } from 'lodash-es';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  defineOptions({ name: 'AccountModal' });

  // 变量定义
  const activeKey = ref('0');
  const previewVisible = ref<boolean>(false);
  const previewImage = ref<string | undefined>('');
  const fileList = ref([]);
  const selectedImagesA = ref([]);
  const selectedImages = ref([]);
  const Data = ref<any>({}); // 定义 Data 为响应式变量
  const chats = ref([
    {
      content: '',
      photos: [],
    },
  ]);
  const comments = ref([
    {
      content: '',
      photos: [],
    },
  ]);
  const tabListTitle = [
    {
      key: '0',
      tab: '手动录入',
    },
    {
      key: '1',
      tab: '筛选',
    },
  ];

  const headerTabListTitle = [
    {
      key: '0',
      tab: '营销任务',
    },
  ];
  const formattedLinks = computed({
    get() {
      return links.value.join(',\n'); // 将数组转换为带逗号和换行符的字符串
    },
    set(value) {
      links.value = value.split(',\n'); // 将带逗号和换行符的字符串转换为数组
    },
  });
  const links = ref<string[]>([]); // 将 links 定义为字符串数组
  const formValue = ref({
    maxNum: '',
    keyWord: '',
    timestamp: '',
  });
  const imgvisible = ref(false);
  const isUpdate = ref(true);
  const rowId = ref('');
  const modalWidth = ref('80%');
  const emit = defineEmits(['success']);
  const total = ref(0);
  const [registerDetailView, { openModal: openDetailView }] = useModal();

  const getTitle = computed(() => (!unref(isUpdate) ? t('sys.configuration.add') : t('sys.configuration.edit')));
  // 定义一个 ref 来引用子组件
  const childComponentRef = ref(null);

  // async function handleOK() {
  //   const commentsWithPhotosString = comments.value.map((comment) => ({
  //     ...comment,
  //     photos: comment.photos.join(','),
  //   }));

  //   const chatsWithPhotosString = chats.value.map((chat) => ({
  //     ...chat,
  //     photos: chat.photos.join(','),
  //   }));

  //   let formattedLinksValue = '';
  //   if (childComponentRef.value) {
  //     formattedLinksValue = childComponentRef.value.getFormattedLinks();
  //   }
  //   const linksArray = formattedLinksValue.split(',').map((link) => link.trim());

  //   const Data = {
  //     ...getFieldsValue(),
  //     comments: commentsWithPhotosString,
  //     chats: chatsWithPhotosString,
  //     photos: selectedImages.value,
  //     links: linksArray,
  //   };
  //   try {
  //     let data;
  //     if (isUpdate.value) {
  //       // 调用编辑接口
  //       let params = {
  //         id: rowId.value,
  //         ...Data,
  //       };
  //       data = await updateTaskApi(params);
  //     } else {
  //       // 调用新增接口
  //       data = await createTaskApi(Data);
  //     }
  //     emit('success', data);
  //     closeModal();
  //   } finally {
  //     setModalProps({ confirmLoading: false });
  //   }
  // }

  function onTabChange(key) {
    activeKey.value = key;
  }

  function add() {
    comments.value.push({ content: '', photos: [] });
  }

  function del(index: number) {
    comments.value.splice(index, 1);
  }

  function addChats() {
    chats.value.push({ content: '', photos: [] });
  }

  function delChats(index: number) {
    chats.value.splice(index, 1);
  }

  function openImageSelector(index: number, type: 'comment' | 'chat') {
    currentIndex.value = index;
    currentType.value = type;
    imgvisible.value = true;
  }

  const currentIndex = ref(-1);
  const currentType = ref<'comment' | 'chat'>('comment');

  function handleOkimg() {
    if (currentIndex.value !== -1) {
      if (currentType.value === 'comment') {
        comments.value[currentIndex.value].photos = selectedImagesA.value;
      } else if (currentType.value === 'chat') {
        chats.value[currentIndex.value].photos = selectedImagesA.value;
      }
    }
    imgvisible.value = false;
    selectedImagesA.value = [];
  }

  function handleUploadChange(info) {
    if (info.file.status === 'done') {
      const response = info.file.response;
      if (response) {
        selectedImages.value.push(response);
      }
    }
  }

  function handleView(record: Recordable) {
    openDetailView(true, {
      record,
    });
  }

  async function getDetail(id) {
    if (id) {
      let Data = await getTaskDetailApi(id);
      if (Data.data.chats) {
        Data.data.chats.forEach((chat) => {
          chat.photos = chat.photos ? chat.photos.split(',') : [];
        });
      }
      if (Data.data.comments) {
        Data.data.comments.forEach((comment) => {
          comment.photos = comment.photos ? comment.photos.split(',') : [];
        });
      }
      if (Data.data.photos) {
        selectedImages.value = Data.data.photos;
        fileList.value = Data.data.photos.map((photoUrl) => ({
          uid: photoUrl, // 假设每个图片 URL 是唯一的标识符
          name: 'image.png', // 可以根据需要设置图片名称
          status: 'done', // 设置图片上传状态为已完成
          url: photoUrl, // 图片 URL
        }));
      }
      chats.value = Data.data.chats;
      comments.value = Data.data.comments;
    }
  }
  const getData = () => {
    const commentsWithPhotosString = comments.value.map((comment) => ({
      ...comment,
      photos: comment.photos.join(','),
    }));

    const chatsWithPhotosString = chats.value.map((chat) => ({
      ...chat,
      photos: chat.photos.join(','),
    }));
    return {
      comments: commentsWithPhotosString,
      chats: chatsWithPhotosString,
      photos: selectedImages.value,
    };
  };

  defineExpose({
    getData,
  });
</script>
